﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace Adams.Admin.DataAccess.Announcements
{
    public static class Index
    {
        public static Adams.Admin.DataTransfer.Announcements.Index.PageLoad PageLoad()
        {
            var data = new Adams.Admin.DataTransfer.Announcements.Index.PageLoad();
            
            return data;
        }

        public static Adams.Admin.DataTransfer.Announcements.Index.GridLoad GridLoad(DataTransfer.GridLoadInput gridinput)
        {
            var data = new Adams.Admin.DataTransfer.Announcements.Index.GridLoad();
            data.Records = new Shared.Entities.Announcements.AnnouncementCollection();

            string filter = string.IsNullOrWhiteSpace(gridinput.Search) ? string.Empty : "FREETEXT ((Title,ShortDescription,LongDescription), '" + gridinput.Search.Replace("'", "''") + "' )";

            string dbq = DB.BuildPagingQuery(gridinput.StartRow, gridinput.PageSize,
                "AnnouncementID,Title,ShortDescription,StartDate,EndDate,Link",
                "Announcements.Announcements",
                filter, string.Empty, gridinput.Sort + " " + gridinput.SortDirection, "AnnouncementID");

            using (SqlDataReader dr = DB.RunDataReader(dbq, CommandType.Text))
            {
                dr.Read();
                data.TotalRecords = dr[0].DbInt();

                dr.NextResult();
                while (dr.Read())
                {
                    var announcement = new Shared.Entities.Announcements.Announcement();
                    announcement.ID = dr["AnnouncementID"].DbInt();
                    announcement.Title = dr["Title"].DbString();
                    announcement.ShortDescription = dr["ShortDescription"].DbString();
                    announcement.StartDate = dr["StartDate"].DbDate();
                    announcement.EndDate = dr["EndDate"].DbDate();
                    announcement.Link = dr["Link"].DbString();
                    data.Records.Add(announcement);
                }
            }

            return data;
        }

        public static void Delete(int id)
        {
            DB.Run(@"
DELETE Announcements.Announcements
WHERE AnnouncementID = @AnnouncementID
", CommandType.Text,
                    DB.CreateParameter("@AnnouncementID", id, SqlDbType.Int));
        }
    }
}
